
var test = 1;
var myDiagram;
var Temp = function(name){
    var res = {};
    res.default = {
        bg:"rgba(66, 87, 109)",
        link:"#999",
        rectb:"rgba(0,0,0,0)",
        rectStock:"#ff882b",
        rectTitle:"#fff",
        rect:"#363636",
        imgProcess:"./assets/img/process.png",
        imgExclusiveGateway:"./assets/img/ExclusiveGateway.png",
        imgParallelGateway:"./assets/img/ParallelGateway.png",
        imgStart:"./assets/img/start.png",
        imgPic:"./assets/img/pic.png",
        imgEnd:"./assets/img/end.png"
    }
    res.temp1 = {
        bg:"rgba(66, 87, 109)",
        link:"#41a627",
        rectb:"#41a627",
        rectStock:"#ff882b",
        rectTitle:"#fff",
        rect:"#0b1530",
        imgProcess:"./assets/img/temp1/icon3.png",
        imgExclusiveGateway:"./assets/img/temp1/icon2.png",
        imgParallelGateway:"./assets/img/temp1/icon.png",
        imgStart:"./assets/img/temp1/star.png",
        imgPic:"./assets/img/pic.png",
        imgEnd:"./assets/img/temp1/end.png"
    }
    res.temp2 = {
        bg:"rgba(66, 87, 109)",
        link:"#5bd6d8",
        rectb:"#5bd6d8",
        rectStock:"#dfb631",
        rectTitle:"#5bd6d8",
        rect:"#0b1530",
        imgProcess:"./assets/img/temp2/icon3.png",
        imgExclusiveGateway:"./assets/img/temp2/icon2.png",
        imgParallelGateway:"./assets/img/temp2/icon.png",
        imgStart:"./assets/img/temp2/star.png",
        imgPic:"./assets/img/pic.png",
        imgEnd:"./assets/img/temp2/end.png"
    }
    res.temp3 = {
        bg:"rgba(66, 87, 109)",
        link:"#0129d0",
        rectb:"#0129d0",
        rectStock:"#00d8fb",
        rectTitle:"#fdd581",
        rect:"#0b1c9d",
        imgProcess:"./assets/img/temp3/icon3.png",
        imgExclusiveGateway:"./assets/img/temp3/icon2.png",
        imgParallelGateway:"./assets/img/temp3/icon.png",
        imgStart:"./assets/img/temp3/star.png",
        imgPic:"./assets/img/pic.png",
        imgEnd:"./assets/img/temp3/end.png"
    }
    return res[Temp.from][name];
}
Temp.from = "default";
var groupTemp = function(name,type){
    var res = {};
    res["裁剪组"] = {
        border:"#3f51b5"
    }
    res["西服十二组"] = {
        border:"#9e9e9e"
    }
    res["西服一组"] = {
        border:"#673ab7"
    }
    res["西服三组"] = {
        border:"#ff5722"
    }
    res["西服五组"] = {
        border:"#ff9800"
    }
    res["整烫组"] = {
        border:"#ffc107"
    }
    res["手工组"] = {
        border:"#ffeb3b"
    }
    res["西服十三组"] = {
        border:"#cddc39"
    }
    res["西服二组"] = {
        border:"#8bc34a"
    }
    res["西服六组"] = {
        border:"#4caf50"
    }
    res["质检组"] = {
        border:"#009688"
    }
    res["西服四组"] = {
        border:"#00bcd4"
    }
    return res[name]?res[name][type]:'';
}


//  graphobject
;(function(){
    var $$ = go.GraphObject.make;  // for more concise visual tree definitions
    var pathMap;
    var mask = (function(){
        var $mask = $('<div id="mask">');
        var $body = $('body');
        $mask.html('<img src="./assets/img/loading.gif" />');
        return {
            open:function(){
                $body.append($mask);
            },
            close:function(){
                $mask.remove();
            }
        }
    }());

    // diagram - 初始化
    function init() {
        if(myDiagram==void 0){
            var config = {
                allowDrop: true,
                //"LinkDrawn": showLinkLabel,  // this DiagramEvent listener is defined below
                //"LinkRelinked": showLinkLabel,
                "rotatingTool.snapAngleMultiple": 90,
                "rotatingTool.snapAngleEpsilon": 45,
                "animationManager.isEnabled": false,
                "initialContentAlignment": go.Spot.Center,
                "undoManager.isEnabled": true,
                "allowZoom":true,
                "padding":new go.Margin(80,80),
                "scale":.7,
                //"layout":$$(go.TreeLayout, {
                //    angle: 0,
                //    arrangement: go.TreeLayout.ArrangementVertical,
                //    isRealtime: false,
                //    layerSpacing: 80,
                //    setsPortSpot: false,
                //    setsChildPortSpot: false
                //})
            }
            myDiagram = $$(go.Diagram, "myDiagramDiv",config);
            myDiagram.toolManager.linkingTool.temporaryLink.routing = go.Link.Orthogonal;
            myDiagram.toolManager.relinkingTool.temporaryLink.routing = go.Link.Orthogonal;
            //myDiagram.contextMenu = $$(go.HTMLInfo, {show: Dialog.showMenu,mainElement: Dialog.$contextMenu[0]});
            loop();
            //
            pathMap || (pathMap = getPathMap());
        }


        myDiagram.startTransaction();
        // diagram - 面板背景
        document.getElementById("myDiagramDiv").style.backgroundColor = Temp("bg");
        // diagram - 元素组件定义
        myDiagram.nodeTemplateMap.add("Process",
            $$(go.Node, "Table", nodeStyle(),  // the whole node panel
                {
                    name:"Process",
                    resizable: false,
                    selectionObjectName: "ICON"
                },
                //$$(go.Panel,{width:1,height:1,name:'ICON',alignment:go.Spot.TopLeft}),
                $$(go.Shape, "RoundedRectangle",
                    {
                        name:"ICON",
                        strokeWidth:2,
                        stroke:Temp("rectb"),
                        fill:Temp("rect"),
                        minSize: new go.Size(230, 100),
                        shadowVisible:true
                    }
                ),
                $$(go.Panel, "Horizontal",
                    $$(go.Picture,Temp("imgProcess"), {
                        desiredSize: new go.Size(30,30),
                        margin:new go.Margin(0,10,0,0),
                        contextMenu:$$(go.HTMLInfo, {
                            show: Dialog.showMenu,
                            mainElement: Dialog.$contextMenu[0]
                        })
                    }),
                    $$(go.TextBlock ,
                        textStyle(12,Temp("rectTitle"),"normal"),
                        {width:160},
                        new go.Binding("text","text")
                    )
                ),
                //$$(go.TextBlock ,
                //    textStyle(12,Temp("rectStock")),
                //    {
                //        alignment:go.Spot.TopRight,
                //        shadowVisible:false
                //    } ,
                //    new go.Binding("text","key",function(key){return "占压: "+key;})
                //),
                // four named ports, one on each side:
                makePort("T", go.Spot.Top, go.Spot.TopCenter, true, true),
                makePort("L", go.Spot.Left, go.Spot.LeftCenter, true, true),
                makePort("R", go.Spot.Right, go.Spot.RightCenter, true, true),
                makePort("B", go.Spot.Bottom, go.Spot.BottomCenter, true, true)
            ));

        myDiagram.nodeTemplateMap.add("ExclusiveGateway",
            $$(go.Node, "Table", nodeStyle(),
                {selectionObjectName: "ICON"},
                $$(go.TextBlock ,
                    textStyle(11,Temp("rectStock")),
                    {margin:new go.Margin(0,0,120,0)},
                    new go.Binding("text","text")
                ),
                $$(go.Panel, "Auto",
                    {
                        name: "LABEL"
                    },
                    $$(go.Panel, "Auto",
                        {alignment: go.Spot.MiddleLeft},
                        $$(go.Picture,Temp("imgExclusiveGateway"),
                            {
                                name:"ICON",
                                desiredSize: new go.Size(80, 80),
                                contextMenu:$$(go.HTMLInfo, {
                                    show: Dialog.showMenu,
                                    mainElement: Dialog.$contextMenu[0]
                                })
                            })
                    )
                ),
                //$$("TreeExpanderButton",{ row: 4, columnSpan: 99, alignment: go.Spot.BottomCenter }),
                // four named ports, one on each side:
                makePort("T", go.Spot.Top, go.Spot.TopCenter, true, true),
                makePort("L", go.Spot.Left, go.Spot.LeftCenter, true, true),
                makePort("R", go.Spot.Right, go.Spot.RightCenter, true, true),
                makePort("B", go.Spot.Bottom, go.Spot.BottomCenter, true, true)
            ));

        myDiagram.nodeTemplateMap.add("ParallelGateway",
            $$(go.Node, "Table", nodeStyle(),
                {selectionObjectName: "ICON"},
                $$(go.TextBlock ,
                    textStyle(11,Temp("rectStock")),
                    {margin:new go.Margin(0,0,120,0)},
                    new go.Binding("text","text")
                ),
                $$(go.Panel, "Auto",
                    {
                        name: "LABEL"
                    },
                    $$(go.Panel, "Auto",
                        {alignment: go.Spot.MiddleLeft},
                        $$(go.Picture,Temp("imgParallelGateway"),
                            {
                                name:"ICON",
                                desiredSize: new go.Size(80, 80),
                                contextMenu:$$(go.HTMLInfo, {
                                    show: Dialog.showMenu,
                                    mainElement: Dialog.$contextMenu[0]
                                })
                            })
                    )
                ),
                //$$("TreeExpanderButton", { row: 4, columnSpan: 99, alignment: go.Spot.BottomCenter }),
                // four named ports, one on each side:
                makePort("T", go.Spot.Top, go.Spot.TopCenter, true, true),
                makePort("L", go.Spot.Left, go.Spot.LeftCenter, true, true),
                makePort("R", go.Spot.Right, go.Spot.RightCenter, true, true),
                makePort("B", go.Spot.Bottom, go.Spot.BottomCenter, true, true)
            ));

        myDiagram.nodeTemplateMap.add("Start",
            $$(go.Node, "Auto", nodeStyle(),
                $$(go.Panel, "Auto",
                    $$(go.Picture,Temp("imgStart"), {desiredSize: new go.Size(100, 100)})
                ),
                // four named ports, one on each side:
                makePort("T", go.Spot.Top, go.Spot.TopCenter, true, true),
                makePort("R", go.Spot.Right, go.Spot.RightCenter, true, true),
                makePort("B", go.Spot.Bottom, go.Spot.BottomCenter, true, true)
            ));

        myDiagram.nodeTemplateMap.add("End",
            $$(go.Node, "Auto", nodeStyle(),
                $$(go.Panel, "Auto",
                    $$(go.Picture,Temp("imgEnd"), {desiredSize: new go.Size(100, 100)})
                ),
                // four named ports, one on each side:
                makePort("T", go.Spot.Top, go.Spot.TopCenter, true, true),
                makePort("L", go.Spot.Left, go.Spot.LeftCenter, true, true),
                makePort("B", go.Spot.Bottom, go.Spot.BottomCenter, true, true)
            ));

        myDiagram.linkTemplate = $$(
            go.Link,
            {
                routing: go.Link.Orthogonal,
                curve: go.Link.JumpOver,
                adjusting: go.Link.Stretch,
                corner: 10,
                smoothness:0 ,// routing:Orthogonal  + curve:Bezier
                relinkableFrom: true,
                relinkableTo: true,
                reshapable: true,
                resegmentable: true,
                selectable: true,      // links be selected by the user
                layerName: "Background",  // don't cross in front of any nodes
                toShortLength: 1
            },
            //new go.Binding("points","points").makeTwoWay(),
            new go.Binding("points","points").makeTwoWay(function(point,node){
                var arr = [];
                point.iterator.each(function(o){
                    if(o.J){
                        arr.push(Math.ceil(o.M))
                        arr.push(Math.ceil(o.N))
                    }
                })
                return arr;
            }),
             new go.Binding("fromPort","fromPort").makeTwoWay(),
             new go.Binding("toPort","toPort").makeTwoWay(),
            // mark each Shape to get the link geometry with isPanelMain: true
            // $$(go.Shape, {stroke: COLOR.link, strokeWidth: 5 })
            $$(go.Shape, { isPanelMain: true, stroke: "#b5b5b5", strokeWidth: 13 }),
            $$(go.Shape, { isPanelMain: true, stroke: Temp("link"), strokeWidth: 12 }),
            $$(go.Shape,{
                isPanelMain: true,
                name: "PIPE",
                strokeWidth: 8,
                stroke: "white",
                strokeDashArray: [10, 10]
                //pathPattern:$$(go.Picture,"./assets/img/arrow.png",
                //    {
                //        name:"ICON",
                //        desiredSize: new go.Size(20, 10)
                //    })
                //pathPattern:$$(go.Shape,{
                //        name:"ICON",
                //        geometryString: "F M0 2 M0 2 L4 2 L4 0 L8 4 L4 8 L4 6 L0 6z M20 2",
                //        fill:"white",
                //        stroke:"transparent"
                //    })
            }),
            $$(go.Panel,"Auto",
                {},
                //new go.Binding("segmentOffset","",function(name){
                //    console.log("segmentoffset",arguments);
                //    return null;
                //}).makeTwoWay(),
                $$(go.Shape,  // the label background, which becomes transparent around the edges
                    {
                        stroke: null
                    },
                    new go.Binding("fill","from",function(name){return name>>0?Temp("bg"):'transparent';}).makeTwoWay()
                ),
                $$(go.Panel,"Vertical",
                    {
                        margin:new go.Margin(10,10)
                    },
                    $$(go.TextBlock, "transition",  // the label text
                        textStyle(12,Temp("rectStock")),
                        {
                            margin:new go.Margin(0,0,10,0),
                            textAlign: "center"
                        },
                        // editing the text automatically updates the model data
                        new go.Binding("text","from",function(name){return name>>0?("占压: "+name):'';}).makeTwoWay()
                    ),
                    $$(go.Picture,Temp("imgPic"),{
                            width:20,
                            height:20,
                            alignment:go.Spot.Center,
                            click:function(){
                                console.log("click")
                            }
                        },
                        new go.Binding("visible","from",function(name){return name>>0?true:false;}).makeTwoWay()
                    )
                )
            )
        );

        // define the group template
        myDiagram.groupTemplate =
            $$(go.Group, "Auto",nodeStyle(),
                {
                    // the group begins unexpanded;
                    // upon expansion, a Diagram Listener will generate contents for the group
                    isSubGraphExpanded: true,
                    //"layout":$$(go.TreeLayout, {
                    //    angle: 0,
                    //    arrangement: go.TreeLayout.ArrangementVertical,
                    //    isRealtime: false,
                    //    layerSpacing: 80
                    //}),
                    // when a group is expanded, if it contains no parts, generate a subGraph inside of it
                    subGraphExpandedChanged: function(group) {
                        if (group.memberParts.count === 0) {
                            //randomGroup(group.data.key);
                        }
                    }
                },
                //new go.Binding("background","key",function(name){
                //    return groupTemp(name,'border')
                //}).makeTwoWay(),
                $$(go.Shape, "Rectangle",
                    {fill: null, stroke: "transparent" , strokeWidth: 2 },
                    new go.Binding("pathPattern","key",function(name){
                        return getPathDot(groupTemp(name,'border'))
                    }).makeTwoWay()
                ),
                $$(go.Panel, "Vertical",
                    { defaultAlignment: go.Spot.LeftCenter, margin: 4 },
                    $$(go.Panel, "Horizontal",
                        { defaultAlignment: go.Spot.TopCenter },
                        // the SubGraphExpanderButton is a panel that functions as a button to expand or collapse the subGraph
                        $$("SubGraphExpanderButton"),
                        $$(go.TextBlock,
                            { font: "Bold 18px Sans-Serif",stroke:"#fff", margin: new go.Margin(10, 10) },
                            new go.Binding("text", "key"))
                    ),
                    // create a placeholder to represent the area where the contents of the group are
                    $$(go.Placeholder,
                        { padding: new go.Margin(0, 10) })
                )  // end Vertical Panel
            );  // end Group

        //
        myDiagram.commitTransaction();

        // helper definitions for node templates
        function showLinkLabel(e) {
            //var label = e.subject.findObject("LABEL");
            //if (label !== null) label.visible = (e.subject.fromNode.data.figure === "Diamond");
        }
        function nodeStyle() {
            return [
                new go.Binding("location", "pos", go.Point.parse).makeTwoWay(function(a){
                    return Math.ceil(a.x.toString())+" "+Math.ceil(a.y.toString())
                })
                //{locationSpot: go.Spot.Center}
            ];
        }
        function textStyle(size,stroke,bold) {
            return {
                wrap: go.TextBlock.OverflowClip,
                stroke: stroke || '',
                font: (bold||'bold') + " " + (size || 11) + "pt Helvetica, Arial, sans-serif"
            }
        }
        function makePort(name, align, spot, output, input) {
            var horizontal = align.equals(go.Spot.Top) || align.equals(go.Spot.Bottom);
            // the port is basically just a transparent rectangle that stretches along the side of the node,
            // and becomes colored when the mouse passes over it
            return $$(go.Shape,
                {
                    fill: "transparent",  // changed to a color in the mouseEnter event handler
                    strokeWidth: 0,  // no stroke
                    width: horizontal ? NaN : 8,  // if not stretching horizontally, just 8 wide
                    height: !horizontal ? NaN : 8,  // if not stretching vertically, just 8 tall
                    alignment: align,  // align the port on the main Shape
                    stretch: (horizontal ? go.GraphObject.Horizontal : go.GraphObject.Vertical),
                    portId: name,  // declare this object to be a "port"
                    fromSpot: spot,  // declare where links may connect at this port
                    fromLinkable: output,  // declare whether the user may draw links from here
                    toSpot: spot,  // declare where links may connect at this port
                    toLinkable: input,  // declare whether the user may draw links to here
                    cursor: "pointer",  // show a different cursor to indicate potential link point
                    mouseEnter: function(e, port) {  // the PORT argument will be this Shape
                        if (!e.diagram.isReadOnly) port.fill = "blue";
                    },
                    mouseLeave: function(e, port) {
                        port.fill = "transparent";
                    }
                });
        }
    };



    //  diagram - 业务函数
    function definePathPattern(geostr, color, width, cap) {
        if (typeof name !== 'string' || typeof geostr !== 'string') throw new Error("invalid name or geometry string argument: " + name + " " + geostr);
        if (color === undefined) color = "black";
        if (width === undefined) width = 1;
        if (cap === undefined) cap = "square";
        return go.GraphObject.make(go.Shape,
            {
                geometryString: geostr,
                fill: "transparent",
                stroke: color,
                strokeWidth: width,
                strokeCap: cap
            }
        );
    }
    function getPathMap(){
        // Define a bunch of small Shapes that can be used as values for Shape.pathPattern
        var PathPatterns = new go.Map('string', go.Shape);
        PathPatterns.add("Dot", definePathPattern("M0 0 M8 0 L8.1 0", "gray", 4, "round"));
        PathPatterns.add("Herringbone", definePathPattern("M0 0 L2 2 L0 4  M1.1 0.1 L2.1 2.1 L1.1 4.1 M10 0 L12 2 L10 4","white",1,"round"));
        PathPatterns.add("Sawtooth", definePathPattern("M0 3 L4 0 2 6 6 3"));
        //
        return function(name){
            return PathPatterns.getValue(name);
        }
    }
    function getPathDot(color){
        return definePathPattern("M0 0 M10 0 L20 0 M30 0",color || "gray", 8, "round");
    }


    function loop() {
        var diagram = myDiagram;
        var hander;
        var func = function() {
            var oldskips = diagram.skipsUndoManager;
            diagram.skipsUndoManager = true;
            diagram.links.each(function(link) {
                var shape = link.findObject("PIPE");
                if(shape){
                    var off = shape.strokeDashOffset - 4;
                    shape.strokeDashOffset = (off <= 0) ? 20 : off;
                }
            });
            diagram.skipsUndoManager = oldskips;
            animation();
        }
        var animation = function(){
            hander = setTimeout(func,200);
        }
        hander || animation();
    }
    function loopLink(path){
        //var val = "F M0 2 M0 2 L4 2 L4 0 L8 4 L4 8 L4 6 L0 6z M20 2";
        var x_arr = [0,4,4,8,4,4,0];
        var arr;
        var str = path.geometryString;
        var offset = str.split(/\s/)[3].replace("M","");
        offset -= 5;
        offset < 0 && (offset = 15);
        arr = x_arr.map(function(v){
            return v + offset;
        });
        console.log(arr.toString());
        path.geometryString = "F M0 2 M"+arr[0]+" 2 L"+arr[1]+" 2 L"+arr[2]+" 0 L"+arr[3]+" 4 L"+arr[4]+" 8 L"+arr[5]+" 6 L"+arr[6]+" 6z M20 2";
    }


    function save(){
        var data = myDiagram.model.toJSON().replace("class","pos");//.replace("class","odid\":\"\",\"pos");
        mask.open();
        $.ajax({
            url:$.baseURI+'/step/pos',
            type:"put",
            contentType:"application/json",
            data:data,
            success:function(res){
                mask.close();
                if(res=="success"){
                    alert("OK");
                }
            },
            error:function(){
                mask.close();
                alert("ERROR");
            }
        })
    }


    function load() {
        var param = location.search, url = $.baseURI+"/step/all?odid=2561576" + param;
        mask.open();
        // ?odid=2561576
        if(test){
            url = './json/data2.json'
        }
        $.getJSON(url,{},function(res){//'./json/data.json'  $.baseURI+"/neo4j/all"
            res.class = "go.GraphLinksModel";
            res.linkFromPortIdProperty =  "fromPort";
            res.linkToPortIdProperty = "toPort";
            res.linkDataArray.map(function(v){
                !v.fromPort && (v.fromPort = "R");
                !v.toPort && (v.toPort = "L");
            })
            if(!res.pos){
                setTimeout(function(){
                    mask.close();
                    myDiagram.layout = go.GraphObject.make(go.Layout)
                },1)
            }else{
                mask.close();
            }
            myDiagram.model = go.Model.fromJson(res);
        })
    }

    //
    $.baseURI = "http://192.168.199.139:8080";
    $.API = {
        init:init,
        save:save,
        load:load,
        //
        theme:function(name){
            Temp.from = name;
            init();
        },
        make:function(res){
            if(res){
                res = localStorage.setItem("json");
                myDiagram.model = go.Model.fromJson(res);
            }else{
                res = myDiagram.model.toJSON();
                localStorage.setItem("json",res);
                return res;
            }
        }
    }
}())
